package cc.shacocloud.luanniao.web.controller

import cc.shacocloud.luanniao.core.model.dto.input.KnowledgeBaseInput
import cc.shacocloud.luanniao.core.model.dto.input.KnowledgeBaseListInput
import cc.shacocloud.luanniao.core.service.AiModelService
import cc.shacocloud.luanniao.core.service.KnowledgeBaseService
import cc.shacocloud.luanniao.web.controller.interceptor.NamespaceCollaboratorsAuth
import cc.shacocloud.luanniao.web.controller.interceptor.NamespaceVisitorsAuth
import cc.shacocloud.luanniao.web.controller.interceptor.UserNamespacePermissionInterceptor.Companion.currentUserNamespaceMo
import cc.shacocloud.luanniao.web.model.convert.toOutput
import cc.shacocloud.luanniao.web.model.dto.output.KnowledgeBaseOutput
import org.springframework.data.domain.Page
import org.springframework.validation.BeanPropertyBindingResult
import org.springframework.validation.BindException
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import org.springframework.web.server.ServerWebExchange

/**
 * 知识库接口
 * @author 思追(shaco)
 */
@Validated
@RestController
@RequestMapping("/api/namespace/{namespaceId}/knowledge-base")
class KnowledgeBaseController(
    val knowledgeBaseService: KnowledgeBaseService,
    val aiModelService: AiModelService,
) {

    /**
     * 知识库列表
     */
    @GetMapping
    @NamespaceVisitorsAuth
    suspend fun list(
        @Validated input: KnowledgeBaseListInput,
        exchange: ServerWebExchange,
    ): Page<KnowledgeBaseOutput> {
        val userNamespaceMo = exchange.currentUserNamespaceMo()
        return knowledgeBaseService.list(input, userNamespaceMo).toOutput()

    }

    /**
     * 创建知识库
     */
    @PostMapping
    @NamespaceCollaboratorsAuth
    suspend fun create(
        @Validated @RequestBody input: KnowledgeBaseInput,
        exchange: ServerWebExchange,
    ): KnowledgeBaseOutput {
        val userNamespaceMo = exchange.currentUserNamespaceMo()

        if (!aiModelService.existsById(input.aiModelId)) {
            val bindingResult = BeanPropertyBindingResult(input, "input")
            bindingResult.rejectValue("aiModelId", "资源不存在")
            throw BindException(bindingResult)
        }

        return knowledgeBaseService.create(input, userNamespaceMo).toOutput()
    }

}